package com.ninong.ker.admin.sevice.impl;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ninong.ker.admin.rest.vo.DeptVO;
import com.ninong.ker.common.auth.SecurityAdmin;
import com.ninong.ker.common.tools.PropertyUtil;
import com.ninong.ker.common.user.OnlineUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ninong.ker.admin.domain.Dept;
import com.ninong.ker.admin.mapper.DeptMapper;
import com.ninong.ker.admin.sevice.DeptService;
import com.ninong.ker.common.exception.CmdException;

/**
 * @author cmd
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

	private static final String PARENT = "0";
	@Autowired
	private SecurityAdmin securityAdmin;

	@Override
	public List<DeptVO> listDeptTree(Dept dto) {
		OnlineUser onlineUser = securityAdmin.currentUser();
		String tenantId = onlineUser.getTenantId();
		dto.setPid(PARENT);
		dto.setTenantId(tenantId);
		return baseMapper.selectDeptTree(dto);
	}

	@Override
	public void delete(String[] ids) {
		baseMapper.deleteBatchIds(Arrays.asList(ids));
	}

	@Override
	public void create(Dept entity) {
		OnlineUser onlineUser = securityAdmin.currentUser();
		String tenantId = onlineUser.getTenantId();
		if(entity.getPid()==null||("").equals(entity.getPid())) {
			entity.setPid(PARENT);
		}
		entity.setTenantId(tenantId);
		//校验部门名称是否重复
		if (this.checkDeptNameExists(entity)) {
			String mess = PropertyUtil.getProperty("DEPT_NAME_REPEAT");
			throw new CmdException(100, mess);
		}
		this.saveOrUpdate(entity);
	}

	/**
	 * 校验部门名称是否重复
	 *
	 * @param entity
	 */
	private boolean checkDeptNameExists(Dept entity) {
		QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(Dept::getName, entity.getName());
		queryWrapper.lambda().eq(Dept::getTenantId, entity.getTenantId());
		if (entity.getId() == null) {
			queryWrapper.isNotNull("id");
		} else {
			queryWrapper.lambda().ne(Dept::getId, entity.getId());
		}
		List<Dept> deptList = baseMapper.selectList(queryWrapper);
		if (deptList != null && deptList.size() > 0) {
			return true;
		}
		return false;
	}

	@Override
	public Dept get(String id) {
		Dept entity = baseMapper.selectById(id);
		if (ObjectUtils.isEmpty(entity)) {
			entity = new Dept();
		}
		Dept dto = new Dept();
		dto.setPid(PARENT);
		OnlineUser onlineUser = securityAdmin.currentUser();
		String tenantId = onlineUser.getTenantId();
		dto.setTenantId(tenantId);
		entity.setResouces(baseMapper.selectDeptTree(dto));
		return entity;
	}
}
